package com.FastTorchPro;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.preference.PreferenceManager;

public final class GlobalLogic{

	public static final int OFF_MODE=0;
	public static final int ON_LED_MODE=1;
	public static final int ON_SCREEN_MODE=2;
	public static final int PREF_MODE=33;
	public static final int EXIT_MODE=100;
	public static final int PAUSE_MODE=10;
	
	public static int curentMode=0;
	public static int oldMode=0;
	
	public static final int RUN_FROM_WIDGET=110;
	public static final int RUN_FROM_ACTIVITY=1000;
	
	public static int runedFrom=RUN_FROM_ACTIVITY;
	
	public static Boolean readyToExitSmall=false;
	public static Boolean readyToExitBig=false;
		
	public static SharedPreferences prefs;
	
	public static Context lastContext=null;
	
	
	public static Boolean isScreenOff=false;
	
	 public static final int NOTIFY_ID = 101; 
	 public static NotificationManager mNotifyMgr; 
	 
	 public static String ACTION_TAKE_RECEIVER = "ActionTake";
	 public static String ACTION_OFF_RECEIVER = "ActionOff";
	 

	 private static Camera camera;
	 private static int cameraId = -1;
		
	 private static void runScreenTorch(Context context){
		
		 	if (MainFastTorchActivity.handleToClose!=null){
		 		MainFastTorchActivity.handleToClose.finish();
		 		MainFastTorchActivity.handleToClose=null;
		 	}
			 Intent runs = new Intent(context, MainFastTorchActivity.class);
			  		 
			 runs.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			 runs.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
			 runs.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			 context.getApplicationContext().startActivity(runs);
			
	  }

	public static int findFrontFacingCamera(Context context) {
		    cameraId = -1;
		    if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
		    	return cameraId;
		    }
		    // Search for the front facing camera
		    int numberOfCameras = Camera.getNumberOfCameras();
		    for (int i = 0; i < numberOfCameras; i++) {
		      CameraInfo info = new CameraInfo();
		      Camera.getCameraInfo(i, info);
		      if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
		      
		        cameraId = i;
		       
		        break;
		      }
		    }
		    return cameraId;
		  }
	 
	private static int onTorch(Context context){
			 
			 findFrontFacingCamera(context);
					
				if (cameraId>=0 && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)){ 
					 
					if (camera==null){
						try {
							camera = Camera.open(cameraId);		
							
							Parameters params = camera.getParameters();			
							params.setFlashMode(Parameters.FLASH_MODE_TORCH);		
							camera.setParameters(params);
							camera.startPreview();
								
							curentMode= ON_LED_MODE;
							 if (!prefs.getBoolean("led_block", false)){
								   resiverRegistred=true;
								   context.getApplicationContext().registerReceiver(torchReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); 
								 
							   } 	
						} catch (RuntimeException e) {	
							 curentMode= ON_SCREEN_MODE;
						}
					}															
				 }
				 else{
					 
					 curentMode= ON_SCREEN_MODE;
				 }
				
				if (runedFrom==RUN_FROM_WIDGET && MainFastTorchActivity.handleToClose!=null){
					  MainFastTorchActivity tmpa=(MainFastTorchActivity)MainFastTorchActivity.handleToClose;
					  tmpa.UpdateState();
				}
				
		return curentMode;
	}
	
	 private static void OffTorch(Context context){
		  
		  if (camera!=null){
			  
			Parameters params = camera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.stopPreview();
	        camera.release();
	            
		  }
		  
		  curentMode=OFF_MODE;
		  camera=null;
		  cameraId=-1;	
		  
		  if (resiverRegistred){
			   context.unregisterReceiver(torchReceiver);	
			   resiverRegistred=false;
			   }
		  
		  prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
		  if (prefs.getBoolean("led_notif", true)){
			  mNotifyMgr.cancel(GlobalLogic.NOTIFY_ID);
	      }
	 }
	
	private static Boolean resiverRegistred=false;
	 private static BroadcastReceiver torchReceiver = new BroadcastReceiver(){  
		  
	     @Override  
	     public void onReceive(Context context, Intent intent) {  
	     
	    	GlobalLogic.isScreenOff=true;
	    	 OffTorch(context);
	       	 prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
	    	 if (!prefs.getBoolean("led_block", false)){				  
	    		 onTorch(context);
	    	 }
	    	 
	     }  
	    
	}; 

	public static void SendNotify(Context context){
		
		prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
		 if (prefs.getBoolean("led_notif", true)){
			 
		 mNotifyMgr = (NotificationManager)context.getSystemService( 
	        		Context.NOTIFICATION_SERVICE); 
			int icon = R.drawable.ic_launcher; 
			
        CharSequence tickerText = context.getString(R.string.app_name); 
        long when = System.currentTimeMillis(); 
        
		 Notification notification = new Notification(icon, tickerText, when);
         notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
       
         CharSequence contentTitle = "FastTorch"; 
         CharSequence contentText = context.getString(R.string.of_light_notif);
         
         Intent notificationIntent = new Intent( 
      		   context, Receiver.class);
         notificationIntent.setAction(ACTION_OFF_RECEIVER);
         
         PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, 0); 
         
                 
         notification.setLatestEventInfo(context, contentTitle, 
                 contentText, contentIntent); 
         
        	 mNotifyMgr.notify(NOTIFY_ID, notification);
         }
                         
	}
	
	public static void closeApp(Context context){
		if (!isScreenOff || prefs.getBoolean("led_block", false)){
			prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
			if (Integer.parseInt(prefs.getString("what_do_p", "0"))!=0){
				if (MainFastTorchActivity.handleToClose!=null){
					MainFastTorchActivity.handleToClose.moveTaskToBack(true);
				}
			}
			else{	
				if (curentMode!=EXIT_MODE){
					if (curentMode==ON_LED_MODE){
						OffTorch(context);
			 		}
					curentMode=EXIT_MODE;		
					updateWidgets(context);
				}
				if (readyToExitBig && readyToExitSmall){
					curentMode=OFF_MODE;
					runedFrom=RUN_FROM_ACTIVITY;
					if (MainFastTorchActivity.handleToClose!=null){
				 		MainFastTorchActivity.handleToClose.finish();
				 		MainFastTorchActivity.handleToClose=null;
				 	}
					//android.os.Process.killProcess(android.os.Process.myPid());
				}		 
			}		 	
		}

		isScreenOff=false;		
	}
	
	public static void updateWidgets(Context context){
		
		Intent intent = new Intent(context,FastTorchWidget.class);
		   intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
		   context.sendBroadcast(intent);
		   
		   intent = new Intent(context,FastTorchBigWidget.class);
		   intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
		   context.sendBroadcast(intent);
	}
	 
	public static int onOffTorch(Context context){
		
		prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
		if (curentMode==PREF_MODE) return PREF_MODE;
		
		if (Integer.parseInt(GlobalLogic.prefs.getString("def_Lihgt", "0"))!=0 && cameraId<=-1){
			curentMode=ON_SCREEN_MODE;
			if (runedFrom==RUN_FROM_WIDGET && !prefs.getBoolean("widget_pref", true)){
				   runScreenTorch(context);
			   }
			return curentMode;
		}
		
	   if (curentMode==OFF_MODE){  
		   
		   if (runedFrom==RUN_FROM_WIDGET && !prefs.getBoolean("widget_pref", true)){
			   runScreenTorch(context);
		   }
		   
		   SendNotify(context);
		   updateWidgets(context);
		   onTorch(context);
		  
		   
		
	   }
		  
	   else if (curentMode==ON_LED_MODE){
		   
		   updateWidgets(context); 
		   OffTorch(context);
		   if (runedFrom==RUN_FROM_WIDGET && !prefs.getBoolean("widget_pref", true)){
			   closeApp(context);
		   }
	   }
	   	  return curentMode;		   
	 }
	
}
